# 文件名: ex6_playwright
# 当前用户: shiping.zheng
# 当前日期: 2025/1/10
# 当前时间: 13:44
# 项目名称: Flag
"""
模块描述:
    playwright不同的异步上下文管理器，cookies复用，避免重复登录
"""

import asyncio
import time

from playwright.async_api import async_playwright
from PIL import Image
import pytesseract
import json

async def main():
    try:
        # 第一个 Playwright 会话：登录并保存 cookies
        async with async_playwright() as p:
            print("Starting first Playwright session")
            browser = await p.chromium.launch(headless=False)
            first_context = await browser.new_context()
            page = await first_context.new_page()
            await page.goto("https://xuntian-test1.tclpv.com/getechLogin")
            # 等待页面加载完成
            time.sleep(2)
            await page.wait_for_load_state('networkidle')
            await page.get_by_placeholder("请输入用户名").fill("admin")
            await page.get_by_placeholder("请输入密码").fill("tcl666")
            # 使用角色选择器定位验证码图片
            captcha_element = page.get_by_role("img").first
            # await captcha_element.click()
            # 获取图片位置
            bounding_box = await captcha_element.bounding_box()
            print("Captcha position:", bounding_box)
            # 保存验证码图片
            await captcha_element.screenshot(path=r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
            # 使用 Tesseract 识别验证码
            captcha_image = Image.open(r'C:\Users\shiping.zheng\Desktop\image\captcha.png')
            captcha_text = pytesseract.image_to_string(captcha_image).strip()
            print("验证码:", captcha_text)

            await page.get_by_placeholder("请输入左图结果").fill(captcha_text)
            await page.get_by_role("button", name="登录").click()

            # 等待页面加载完成
            await page.wait_for_load_state('networkidle')
            time.sleep(4)
            # 保存 cookies
            cookies = await first_context.cookies()
            with open('cookies.json', 'w') as f:
                json.dump(cookies, f)
            print("Saved cookies:", cookies)

            await browser.close()
            print("First Playwright session completed")

        # 第二个 Playwright 会话：加载 cookies 并使用
        async with async_playwright() as p:
            print("Starting second Playwright session")
            browser = await p.chromium.launch(headless=False)
            context = await browser.new_context()
            with open('cookies.json', 'r') as f:
                cookies = json.load(f)
                await context.add_cookies(cookies)

            page = await context.new_page()
            await page.goto('https://xuntian-test1.tclpv.com/operationCenter/equipmentCenter')

            # 等待页面加载完成
            await page.wait_for_load_state('networkidle')

            await browser.close()
            print("Second Playwright session completed")

    except Exception as e:
        print(f"An error occurred: {e}")

# 运行主函数
asyncio.run(main())